package services

import (
	"context"
	"errors"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo"

	"zwai-app/db"
	"zwai-app/models"
)

// InvitedUser 用于返回邀请列表中的每位用户信息
type InvitedUser struct {
	UserID   string `json:"userId"`
	Account  string `json:"account"`
	Username string `json:"username"`
}

// GetCurrentUser 根据用户 ID（hex 字符串）查询 User 和 UserProfile
func GetCurrentUser(ctx context.Context, userIDStr string) (*models.User, *models.UserProfile, error) {
	// 1. 转回 ObjectID
	uid, err := primitive.ObjectIDFromHex(userIDStr)
	if err != nil {
		return nil, nil, errors.New("invalid user ID")
	}

	// 2. 查 User
	var u models.User
	userColl := db.Client.Database(db.DBName).Collection("User")
	if err := userColl.FindOne(ctx, bson.M{"_id": uid}).Decode(&u); err != nil {
		if err == mongo.ErrNoDocuments {
			return nil, nil, errors.New("user not found")
		}
		return nil, nil, err
	}

	// 3. 查 UserProfile
	var p models.UserProfile
	profColl := db.Client.Database(db.DBName).Collection("UserProfile")
	if err := profColl.FindOne(ctx, bson.M{"userId": uid}).Decode(&p); err != nil {
		if err == mongo.ErrNoDocuments {
			// 没有详情也算成功，只返回基本信息
			return &u, nil, nil
		}
		return &u, nil, err
	}

	return &u, &p, nil
}

// GetInvitedUsers 返回当前用户邀请的所有用户简要信息
func GetInvitedUsers(ctx context.Context, userIDStr string) ([]InvitedUser, error) {
	uid, err := primitive.ObjectIDFromHex(userIDStr)
	if err != nil {
		return nil, errors.New("invalid user ID")
	}

	// 1. 拿到邀请人详情里的 invited 列表
	profColl := db.Client.Database(db.DBName).Collection("UserProfile")
	var p models.UserProfile
	if err := profColl.FindOne(ctx, bson.M{"userId": uid}).Decode(&p); err != nil {
		if err == mongo.ErrNoDocuments {
			return nil, nil
		}
		return nil, err
	}

	// 2. 根据 ID 列表批量查 User（也可以用 Find with $in）
	userColl := db.Client.Database(db.DBName).Collection("User")
	cursor, err := userColl.Find(ctx, bson.M{"_id": bson.M{"$in": p.Invited}})
	if err != nil {
		return nil, err
	}
	defer cursor.Close(ctx)

	var invitedList []InvitedUser
	for cursor.Next(ctx) {
		var u models.User
		if err := cursor.Decode(&u); err != nil {
			continue
		}
		invitedList = append(invitedList, InvitedUser{
			UserID:   u.ID.Hex(),
			Account:  u.Account,
			Username: u.Username,
		})
	}
	return invitedList, nil
}
